// directives/permission.ts
import { useAccessStore } from '@/store';
import type { Directive, DirectiveBinding } from 'vue';
import { router } from '@/router';

export const vPermission: Directive = {
  mounted(el: HTMLElement, binding: DirectiveBinding<string>) {
    checkPermission(el, binding);
  },
  updated(el: HTMLElement, binding: DirectiveBinding<string>) {
    checkPermission(el, binding);
  },
};

function checkPermission(el: HTMLElement, binding: DirectiveBinding<string>) {
  const accessStore = useAccessStore();

  // 通过 router.currentRoute.value 获取当前路由
  const routeName = router.currentRoute.value.name;

  // 检查路由名称是否存在且为字符串
  if (typeof routeName !== 'string') {
    console.error('路由名称未定义或不是字符串');
    el?.remove();
    return;
  }
  // 获取指令绑定的权限标识（如 `dashboard:add`）
  const requiredPermission = binding.value;

  // 从 Store 中获取当前路由的权限列表
  const permissions = accessStore.accessPerms[routeName];

  // 检查权限是否存在
  if (!permissions?.includes(requiredPermission)) {
    el.remove();
  }
}
